package com.onenine.app.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.adapter.RechargeAdapter;
import com.onenine.app.fragment.MineFragment;
import com.onenine.app.model.RechargeItem;
import com.onenine.app.request.CommonRequest;
import com.onenine.app.request.ReChargeRequest;
import com.onenine.app.response.AliRechargeResponse;
import com.onenine.app.response.GetRechargeResponse;
import com.onenine.app.response.MyAccountResponse;
import com.onenine.app.response.WxRechargeResponse;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.base.BaseEventActivity;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.tab.CommonTabLayout;
import com.onenine.base.tab.listener.CustomTabEntity;
import com.onenine.base.tab.listener.OnTabSelectListener;
import com.onenine.base.tab.utils.TextTabEntity;
import com.onenine.base.utils.ItemSpacesDecoration;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.SizeUtils;
import com.umeng.share.AliPayMgr;
import com.umeng.share.AliPayResult;
import com.umeng.share.WxPayMgr;
import com.umeng.share.WxPayRequest;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 充值
 */
public class RechargeActivity extends BaseEventActivity implements View.OnClickListener
        , BaseQuickAdapter.OnItemClickListener, OnTabSelectListener {

    private RecyclerView mRvCommon;
    private Button mBtnConfirm;
    private TextView mTvProtocol, tvDiamondNum;
    private CommonTabLayout mTabLayout;
    private RechargeAdapter mAdapterCommon;
    private RechargeItem mCurrentRechargeItem;
    private View mCurrentItemView;
    private int mTabPosition;

    public static void launchActivity(Context context) {
        Intent intent = new Intent(context, RechargeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_recharge;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setCenterTitle(R.string.buy_diamond);
        mToolbar.setRightTitle(R.string.recharge_detail);
        mToolbar.setRightTitleColor(ActivityCompat.getColor(this, R.color.c999));
        mRvCommon = findViewById(R.id.rv_common);
        mRvCommon.setLayoutManager(new GridLayoutManager(this, 3));
        mBtnConfirm = findViewById(R.id.btn_confirm_recharge);
        mTabLayout = findViewById(R.id.ctl_tab);
        View topView = findViewById(R.id.ll_top_bg);
        topView.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.IC_RECHARGE_TOP_BG));
        mBtnConfirm.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_GRADIENT_CORNER_BG));
        mTvProtocol = findViewById(R.id.tv_user_protocol);
        mTvProtocol.setTextColor(RoleResLoader.getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR));
        int margin = SizeUtils.dp2px(5);
        mRvCommon.addItemDecoration(new ItemSpacesDecoration(margin, margin, margin, margin));
        tvDiamondNum = findViewById(R.id.tv_my_balance);
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mToolbar.setOnRightClickListener(this);
        mBtnConfirm.setOnClickListener(this);
        mTvProtocol.setOnClickListener(this);
        mTabLayout.setOnTabSelectListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        initTabData();
        getMyAccount();
        loadRechargeList();
    }

    /**
     * 初始化tab
     */
    private void initTabData() {
        ArrayList<CustomTabEntity> dataEntity = new ArrayList<>();
        String[] tabTitles = getResources().getStringArray(R.array.recharge_tab_type);
        for (String title : tabTitles) {
            dataEntity.add(new TextTabEntity(title));
        }
        mTabLayout.setTabData(dataEntity);
        mTabLayout.setCurrentTab(0);
    }

    /**
     * 获取当前用户资产信息
     */
    private void getMyAccount() {
        OkRequest.getInstance().withUrl(UrlConfig.GET_ACCOUNT)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest(MineFragment.class.getSimpleName(), new OkCallback<MyAccountResponse>() {
                    @Override
                    public void onResponse(MyAccountResponse response, String srcData) {
                        if (response.isSuccess()) {
                            tvDiamondNum.setText(response.getAvailableDiamond() + "");
                        }
                    }
                });
    }

    /**
     * 加载充值列表
     */
    private void loadRechargeList() {
        showLoading();
        OkRequest.getInstance().withUrl(UrlConfig.GET_RECHARGE_LIST)
                .withRequest(new CommonRequest(RcUser.getInstance().getUserId()))
                .doRequest(RechargeActivity.class.getSimpleName(), new OkCallback<GetRechargeResponse>() {
                    @Override
                    public void onResponse(GetRechargeResponse response, String srcData) {
                        dismissLoading();
                        if (response.isSuccess()) {
                            showRechargeItems(response.getRechargeItemList());
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    /**
     * 生成支付订单
     *
     * @param payType
     * @param money
     */
    private void createPayOrder(int payType, String pkId, String money) {
        ReChargeRequest request = new ReChargeRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setPayType(payType);
        request.setRechargeMoney(money);
        request.setMaintainPkId(pkId);
        OkRequest.getInstance().withUrl(UrlConfig.DEAL_RECHARGE)
                .withRequest(request).doRequest(MineFragment.class.getSimpleName(), getPayCallback(payType));
    }

    /**
     * 发起支付
     *
     * @param payType
     * @return
     */
    private OkCallback getPayCallback(int payType) {
        if (payType == DataType.PAY_ALI) {
            return new OkCallback<AliRechargeResponse>() {
                @Override
                public void onResponse(AliRechargeResponse response, String srcData) {
                    dismissLoading();
                    if (response.isSuccess()) {
                        //发起支付宝支付
                        if (!RechargeActivity.this.isFinishing()) {
                            AliPayMgr.getInstance().sendPay(RechargeActivity.this, response.getOrderInfo());
                        }
                    } else {
                        Toasty.showNormal(response.getMessage());
                    }
                }
            };
        } else {
            return new OkCallback<WxRechargeResponse>() {
                @Override
                public void onResponse(WxRechargeResponse response, String srcData) {
                    dismissLoading();
                    if (response.isSuccess()) {
                        //发起微信支付
                        if (!WxPayMgr.getInstance().isWXAppInstalled()) {
                            Toasty.showNormal(R.string.wx_uninstalled);
                            return;
                        }
                        WxPayRequest payRequest = new WxPayRequest.Builder().setAppId(response.getAppid())
                                .setNonceStr(response.getNoncestr()).setPackageValue(response.getPackageValue())
                                .setPartnerId(response.getPartnerid()).setPrepayId(response.getPrepayid()).setAppId(response.getAppid())
                                .setSign(response.getSign()).setTimestamp(response.getTimestamp()).build();
                        WxPayMgr.getInstance().sendPay(payRequest);
                    } else {
                        Toasty.showNormal(response.getMessage());
                    }
                }
            };
        }
    }

    private void showRechargeItems(List<RechargeItem> commonItems) {
        if (!commonItems.isEmpty()) {
            mAdapterCommon = new RechargeAdapter(commonItems);
            mRvCommon.setAdapter(mAdapterCommon);
            mAdapterCommon.setOnItemClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right_title:
                ActivityUtils.startActivity(this, ConsumeListActivity.class);
                break;
            case R.id.btn_confirm_recharge:
                if (mTabPosition == 1) {
                    Toasty.showNormal("暂不支持支付宝支付");
                    return;
                }
                if (mTabPosition == 2) {
                    Toasty.showNormal("金币兑换正在开发中");
                    return;
                }
                if (mCurrentRechargeItem == null) {
                    Toasty.showNormal(R.string.select_recharge_amount);
                    return;
                }
                showLoading();
                createPayOrder(true ? DataType.PAY_WEIXIN : DataType.PAY_ALI
                        , mCurrentRechargeItem.getMaintainPkId(), mCurrentRechargeItem.getRechargeMoney());
                break;
            case R.id.tv_user_protocol:
                Toasty.showNormal("跳转充值协议");
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AliPayResult result) {
        if (result != null) {

        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (mCurrentItemView == view) {
            return;
        }
        mAdapterCommon.setItemSelected(view, mCurrentItemView);
        mCurrentItemView = view;
        mCurrentRechargeItem = (RechargeItem) adapter.getItem(position);
    }

    @Override
    public void onTabSelect(int position) {
        mTabPosition = position;
    }

    @Override
    public void onTabReselect(int position) {

    }

}
